using Identity.Application.Contracts.Common;
using Identity.Application.PermissionKeyResourceIds.Interfaces;
using Identity.Application.Permissions.Commands;
using Identity.Application.Permissions.Interfaces;
using Identity.Domain.Aggregates;
using MediatR;

namespace Identity.Application.Permissions.CommandHandlers;


public class CreatePermissionCommandHandler : IRequestHandler<CreatePermissionCommand, Result>
{
    private readonly IPermissionsRepository _permissionsRepository;
    private readonly IApiPermissionBindingReadService _apiPermissionBindingReadService;
    private readonly IUnitOfWork _unitOfWork;
    public CreatePermissionCommandHandler(IPermissionsRepository permissionsRepository, IApiPermissionBindingReadService apiPermissionBindingReadService, IUnitOfWork unitOfWork)
    {
        _permissionsRepository = permissionsRepository;
        _apiPermissionBindingReadService = apiPermissionBindingReadService;
        _unitOfWork = unitOfWork;
    }
    public async Task<Result> Handle(CreatePermissionCommand request, CancellationToken cancellationToken)
    {
        var permission = Permission.Create(request.key, request.name, request.description);

        await _permissionsRepository.AddAsync(permission);

        await _unitOfWork.SaveChangesAsync(cancellationToken);

        var apipermission = await _apiPermissionBindingReadService.GetBindingsByPermissionKeyAsync(permission.Key);
        var serviceName = apipermission.ToList().FirstOrDefault()?.fromServiceName;
        return Result.Success(new PermissionDto(permission.Id, permission.Name, permission.Key, permission.Description, serviceName, !string.IsNullOrWhiteSpace(serviceName)));
    }
}
